﻿
var db = require("./db");
var express = require('express')
  , path = require('path')
  , app = express()
  , server = require('http').createServer(app)
  , io = require('socket.io').listen(server)
  , allsockets = {};
  
 var port=3001;
  
var roomInfo = [];


io.set('log level', 1); 


io.on('connection', function (socket) {
  socket.emit('open');//
     console.log("conn",new Date());
  var mycode="";
  
  var client = {
    socket:socket,
    name:false
  }
  var roomnum='';
  //conn
   socket.on('conn', function(msg){
	   console.log("conn"+msg);
		if (roomInfo.indexOf(msg) != -1) { 
		  
		} else {
		 
		  mycode=msg;
		  roomInfo.push(msg);

      db.execute('update danwei set online=1,jointime=? where code=?',[new Date(),msg])
		
		
			socket.emit('conn',"ok");  
		}
		
		
	
		

		
   });
   

   //broadcast
   socket.on('broadcast', function(msg){
	    console.log('msg',msg);
		  io.emit('broadcast', msg);
		
		
  });

  

    socket.on('disconnect', function (data) {  
		
		//console.log("disconnect:"+data);
		roomInfo.splice(roomInfo.indexOf(mycode), 1);

		
    db.execute('update danwei set online=0,outtime=? where code=?',[new Date(),mycode])
		
		
    });


});




app.set(function(){
  app.set('port', process.env.PORT || port);
  app.set('views', __dirname + '/views');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.set('development', function(){
  app.use(express.errorHandler());
});


app.get('/getroom', function(req, res){
  res.send(roomInfo[req.query.roomid]);
});

server.listen(port, function(){
  console.log("yang:Express  server listening on port "+port);
});

var getTime=function(){
  var date = new Date();
  return date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
}

